import logging
import os
import subprocess
import shutil
from typing import List

logger = logging.getLogger(__name__)


def clone_repo(repo_url: str, target_dir: str, branch: str = 'main') -> bool:
    """
    克隆Git仓库到指定目录
    
    Args:
        repo_url: Git仓库URL
        target_dir: 目标目录
        branch: 要克隆的分支名称
        
    Returns:
        bool: 是否成功
    """
    try:
        # 如果目标目录已存在，先删除
        if os.path.exists(target_dir):
            shutil.rmtree(target_dir)
        
        # 克隆指定分支
        result = subprocess.run([
            'git', 'clone',
            '-b', branch,  # 指定分支
            '--single-branch',  # 只克隆指定分支
            repo_url,
            target_dir
        ], capture_output=True, text=True)
        
        if result.returncode != 0:
            print(f"克隆仓库失败: {result.stderr}")
            return False
            
        return True
    except Exception as e:
        print(f"克隆仓库时出错: {str(e)}")
        return False


def list_source_files(project_path: str, extensions: List[str]) -> List[str]:
    """
    列出项目中的所有源文件
    
    Args:
        project_path: 项目路径
        extensions: 文件扩展名列表
        
    Returns:
        List[str]: 源文件路径列表
    """
    source_files = []
    
    for root, _, files in os.walk(project_path):
        for file in files:
            if any(file.endswith(ext) for ext in extensions):
                source_files.append(os.path.join(root, file))
    
    return source_files


def cleanup_repo(repo_dir: str) -> None:
    """
    清理仓库目录
    
    Args:
        repo_dir: 仓库目录
    """
    try:
        if os.path.exists(repo_dir):
            import shutil
            shutil.rmtree(repo_dir, ignore_errors=True)
            logger.info(f"已清理目录: {repo_dir}")
    except Exception as e:
        logger.error(f"清理目录失败: {str(e)}")
